/**
 * 检测组件
 * （ 组件体积较大  要考虑后续优化 ）
 */

const qualityInspectionTestCom = {
    extends: extendsQ,
    props: {
        // 弹框来源  1 添加检测  |  2 开始检测  |  3 重检
        dialogSource: {
            type: [Number, String],
            default: 1
        },
        // 开始检测 | 重检 数据
        options: {
            type: Object,
            default: () => ({})
        }
    },
    template: `
        <div class="start-test-box-big">
            <div class="start-test-box" v-loading="definiteLoading" element-loading-text="计算中···">
                <el-button class="start-test-back" @click="testBackHandle" size="medium" plain>返 回</el-button>
                <!-- 左侧步骤条 -->
                <div class="steps-box">
                    <el-steps direction="vertical" :active="testActice">
                        <el-step title="稻米来源"></el-step>
                        <el-step title="检测"></el-step>
                        <el-step title="检测结果"></el-step>
                    </el-steps>
                </div>
                <!-- 右侧步骤条内容 -->
                <div class="steps-content">
                    <div class="steps-content-box">
                        <div class="steps-roce-source">
                            <div class="_flex">
                                <div>
                                    <span>申请编号</span>
                                    <el-input disabled size="medium" style="width:13vw" v-model="riceSource.number" placeholder="请填写编号"></el-input>
                                </div>
                                <div class="_left">
                                    <span>所属种植户</span>
                                    <el-select :disabled="dialogSource != 1" filterable v-model="riceSource.planter" size="medium" style="width:13vw" placeholder="请选择种植户">
                                        <el-option v-for="(item,index) in planterList" :key="index + 'select'" :label="item.user_name" :value="item.id">
                                        </el-option>
                                    </el-select>
                                </div>
                                <div class="_left">
                                    <span>联系电话</span>
                                    <el-input :disabled="dialogSource != 1" size="medium" style="width:13vw" v-model="riceSource.phone" placeholder="请填写联系电话"></el-input>
                                </div>
                                <div class="_left">
                                    <span>所属监测点</span>
                                    <el-select :disabled="dialogSource != 1" filterable v-model="riceSource.monPoint" size="medium" style="width:13vw" placeholder="请选择监测点">
                                        <el-option v-for="(item,index) in monitoringPointList" :key="index + 'select'" :label="item.label" :value="item.value">
                                        </el-option>
                                    </el-select>
                                </div>
                            </div>
                            <div class="_flex" style="margin-top:20px">
                                <div>
                                    <span>所属稻种</span>
                                    <el-cascader :show-all-levels="false" v-model="riceSource.seedRice" size="medium" style="width:13vw" placeholder="请选择稻种" v-model="riceSource.seedRice" :options="seedRiceList" :props="seedProps">
                                    </el-cascader>
                                </div>
                                <div class="_left">
                                    <span>所属米种</span>
                                    <el-select filterable v-model="riceSource.riceSpecies" size="medium" style="width:13vw" placeholder="请选择米种">
                                        <el-option v-for="(item,index) in riceTypeList" :key="index + 'select'" :label="item.label" :value="item.value">
                                        </el-option>
                                    </el-select>
                                </div>
                                <div class="_left">
                                    <span>播种日期</span>
                                    <el-date-picker :disabled="dialogSource != 1" size="medium" style="width:13vw" value-format="yyyy-MM-dd" v-model="riceSource.date" type="date" placeholder="请选择播种日期">
                                    </el-date-picker>
                                </div>
                                <div class="_left">
                                    <span>样品重量( 克 )</span>
                                    <el-input size="medium" type="number" style="width:13vw" v-model="riceSource.sampleWeight" placeholder="请填写样品重量"></el-input>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="steps-content-box">
                        <span class="second-title">请按照大米检测照片拍摄要求拍摄 详情</span>
                        <el-upload :disabled="stepSecondDisabled" class="avatar-uploader" :action="uploadImgAction" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-error="handleAvatarError">
                            <img v-if="secondTest.imageUrl" :src="secondTest.imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <el-button :disabled="stepSecondDisabled" type="primary" size="medium" @click="definiteCalculationClick">确定计算</el-button>
                    </div>
                    <div class="steps-content-box">
                        <span class="third-steps-title">( 标准：<a @click="testDialogClick" href="javascript:;">NYT 593-2021</a> )</span>
                        <div class="third-box">
                            <div class="third-half-box">
                                <div class="third-left-title">
                                    外观品质
                                </div>
                                <div class="third-right-content">
                                    <div v-if="riceSource.riceSpecies == 2 || riceSource.riceSpecies == 4">
                                        <span>整粳米率( % )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.zjml" placeholder=""></el-input>
                                    </div>
                                    <div class="_left" v-if="riceSource.riceSpecies == 1 || riceSource.riceSpecies == 3">
                                        <span>整粳米率_长粒( % )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.zjmlcl" placeholder=""></el-input>
                                    </div>
                                    <div class="_left" v-if="riceSource.riceSpecies == 1 || riceSource.riceSpecies == 3">
                                        <span>整粳米率_中粒( % )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.zjmlzl" placeholder=""></el-input>
                                    </div>
                                    <div class="_left" v-if="riceSource.riceSpecies == 1 || riceSource.riceSpecies == 3">
                                        <span>整粳米率_短粒( % )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.zjmldl" placeholder=""></el-input>
                                    </div>
                                    <div class="_left" v-show="riceSource.riceSpecies == 1 || riceSource.riceSpecies == 2">
                                        <span>垩白度( % )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.ebd" placeholder=""></el-input>
                                    </div>
                                    <div class="_left" v-show="riceSource.riceSpecies == 1 || riceSource.riceSpecies == 2">
                                        <span>透明度( 级 )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.tmd" placeholder=""></el-input>
                                    </div>
                                    <div class="_left" v-show="riceSource.riceSpecies == 3 || riceSource.riceSpecies == 4">
                                        <span>阴糯米率( % )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.ynml" placeholder=""></el-input>
                                    </div>
                                    <div class="_left" v-show="riceSource.riceSpecies == 3 || riceSource.riceSpecies == 4">
                                        <span>白度( 级 )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.bd" placeholder=""></el-input>
                                    </div>
                                </div>
                            </div>
                            <div class="third-half-box">
                                <div class="third-left-title">
                                    蒸煮食用
                                </div>
                                <div class="third-right-content">
                                    <div>
                                        <span>感官评价( 分 )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.ggpf" placeholder=""></el-input>
                                    </div>
                                    <div class="_left">
                                        <span>碱消值( 级 )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.jxz" placeholder=""></el-input>
                                    </div>
                                    <div class="_left">
                                        <span>胶稠度( mm )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.jcd" placeholder=""></el-input>
                                    </div>
                                    <div class="_left">
                                        <span>直链淀粉（干基）( % )</span>
                                        <el-input :disabled="stepThirdDisabled" size="medium" style="width:10vw" v-model="thirdResults.zldf" placeholder=""></el-input>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <el-button :disabled="stepThirdDisabled" style="margin-top:10px" type="primary" size="medium" @click="evaluateClick">评 价</el-button>
                    </div>
                </div>
            </div>
            <!-- 查看标准弹框 -->
            <div class="pdf-dialog">
                <el-dialog title="提示" :visible.sync="testDialogVisible" width="80%">
                    <div class="dialog-contnet-t">
                        <div class="dialog-close-icon">
                            <i class="el-icon-close" @click="testDialogVisible = false"></i>
                        </div>
                        <iframe style="width: 100%;height: 100%;" src="../../resources/file/NYT 593-2021.pdf" frameborder="0"></iframe>
                    </div>
                </el-dialog>
            </div>
            <!-- 检测结果弹框 -->
            <div class="test-result-box" v-if="testResultDialog">
                <el-dialog title="检测结果" :visible.sync="testResultDialog" width="770px">
                    <div class="test-result-dialog-contnet">
                        <div class="test-resoult-dialog-top">
                            <h2>基本信息</h2>
                            <div class="dialog-top-big-box">
                                <div class="dialog-top-content">
                                    <div>
                                        <span>种植大户：</span>
                                        <span>{{getSeedRiceName(riceSource.planter,planterList,"id","user_name")}}</span>
                                    </div>
                                    <div>
                                        <span>联系电话：</span>
                                        <span>{{riceSource.phone}}</span>
                                    </div>
                                    <div>
                                        <span>所属监测点：</span>
                                        <span>0</span>
                                    </div>
                                </div>
                                <div class="dialog-top-content">
                                    <div>
                                        <span>播种日期：</span>
                                        <span>{{riceSource.date}}</span>
                                    </div>
                                    <div>
                                        <span>所属稻种：</span>
                                        <span>{{getSeedRiceName(riceSource.seedRice,seedRiceList,"id","variety_name")}}</span>
                                    </div>
                                    <div>
                                        <span>所属米种：</span>
                                        <span>{{getSeedRiceName(riceSource.riceSpecies,riceTypeList,"value","label")}}</span>
                                    </div>
                                </div>
                                <div class="dialog-top-content">
                                    <div style="width: 100%;">
                                        <span>备注：</span>
                                        <span>{{options.remark || ""}}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="test-resoult-dialog-top" style="height: 80px">
                            <h2>检测结果</h2>
                            <div class="dialog-bottom-big-box">
                                <div class="dialog-bottom-content">
                                    <div class="dialog-bottom-content-left">
                                        {{getSeedRiceName(testResultData,numberList, "value", "label")}}
                                    </div>
                                    <div class="dialog-bottom-content-left">
                                        <img :src="'../../resources/img/img_' + testResultData + '.png'" alt="级别图">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="testRecheckDialog">重 检</el-button>
                        <el-button type="primary" @click="testResultDialogDefin">确 定</el-button>
                    </span>
                </el-dialog>
            </div>
        </div>
    `,
    data() {
        return {
            // 开始检测步骤条值
            testActice: 0,
            // 种植户下拉列表
            planterList: [],
            // 监测点下拉列表
            monitoringPointList: [],
            // 所属稻种下拉框配置
            seedProps: {
                value: "id",
                label: "variety_name"
            },
            // 步骤一 稻米来源
            riceSource: {
                number: "",
                planter: "",
                phone: "",
                monPoint: "",
                seedRice: "",
                riceSpecies: 1,
                date: "",
                sampleWeight: 200
            },
            // 步骤二 检测
            secondTest: {
                imageUrl: "",
                imageName: "",
                imageId: ""
            },
            // 上传图片接口
            uploadImgAction: GLOBAL_CONFIG.getVirtualPath() + "/api_server/img-definition/upload",
            // 计算加载动画
            definiteLoading: false,
            // 步骤三 检测结果
            thirdResults: {
                ggpf: "",
                jxz: "",
                jcd: "",
                zldf: ""
            },

            // 检测结果标准查看 pdf 弹框
            testDialogVisible: false,

            // 检测结果弹框显示隐藏
            testResultDialog: false,

            // 检测结果值
            testResultData: "",
        }
    },
    computed: {
        // 步骤二 表单限制
        stepSecondDisabled() {
            return this.testActice < 1
        },
        // 步骤三表单限制
        stepThirdDisabled() {
            return this.testActice < 2
        }
    },
    watch: {
        // 步骤一  表单数据判断
        riceSource: {
            handler(newVal, oldVal) {
                let next = true;
                for (let v in newVal) {
                    if (!newVal[v]) {
                        next = false
                    }
                }
                if (next && this.testActice == 0) {
                    this.testActice = 1
                }
            },
            deep: true
        },
        // 获取传参数据  进行赋值
        options(val) {
            this.riceSource = {
                number: val.apply_number,
                planter: val.create_user_id.toString(),
                phone: val.phone,
                monPoint: val.point_id || "0",
                seedRice: Number(val.seed_rice_id) || "",
                riceSpecies: Number(val.rice_species) || 1,
                date: val.sow_date
            }
            if (this.dialogSource == 3) {
                this.testActice = 2
                this.handleRecheckParams(val)
            }
        }
    },
    methods: {
        /**
         * 返回点击
         */
        testBackHandle() {
            this.$emit("test-back")
        },
        /**
         * 获取申请编号
         */
        getApplyNumber() {
            tpHttp.post(this, "action=com.top.riceInstituteQuality.qualityEva.generatedNumber", {}, (data, code, message) => {
                if (code == 0 && data) {
                    this.riceSource.number = data;
                }
            })
        },
        /**
         * 处理重检传参数据回显
         * @param { * } params 重检数据
         */ 
        handleRecheckParams(params) {
            this.secondTest = {
                imageUrl: params?.rice_analysis?.img_url,
                imageName: params?.rice_analysis?.img_ori_name,
                imageId: params?.rice_analysis?.img_id
            }
            let test_result
            if (params?.rice_analysis?.test_result) {
                test_result = JSON.parse(params?.rice_analysis?.test_result)
            } else {
                test_result = {}
            }
            
            this.thirdResults = {
                ggpf: test_result.cook_eat_sense ?? "",
                jxz: test_result.cook_eat_subtraction ?? "",
                jcd: test_result.cook_eat_gel_consistency ?? "",
                zldf: test_result.cook_eat_amylose ?? ""
            }
            this.riceSource.sampleWeight = test_result.sample_weight
            if (this.riceSource.riceSpecies == 1) {
                this.thirdResults.zjmlcl = test_result.whole_rice_precision_long ?? ""
                this.thirdResults.zjmlzl = test_result.whole_rice_precision_middle ?? ""
                this.thirdResults.zjmldl = test_result.whole_rice_precision_short ?? ""
                this.thirdResults.ebd = test_result.evil_whiteness ?? ""
                this.thirdResults.tmd = test_result.pellucidity ?? ""
            } else if (this.riceSource.riceSpecies == 2) {
                this.thirdResults.zjml = test_result.whole_rice_precision ?? ""
                this.thirdResults.ebd = test_result.evil_whiteness ?? ""
                this.thirdResults.tmd = test_result.pellucidity ?? ""
            } else if (this.riceSource.riceSpecies == 3) {
                this.thirdResults.zjmlcl = test_result.whole_rice_precision_long ?? ""
                this.thirdResults.zjmlzl = test_result.whole_rice_precision_middle ?? ""
                this.thirdResults.zjmldl = test_result.whole_rice_precision_short ?? ""
                this.thirdResults.ynml = test_result.negative_rate ?? ""
                this.thirdResults.bd = test_result.whiteness ?? ""
            } else if (this.riceSource.riceSpecies == 4) {
                this.thirdResults.zjml = test_result.whole_rice_precision ?? ""
                this.thirdResults.ynml = test_result.negative_rate ?? ""
                this.thirdResults.bd = test_result.whiteness ?? ""
            }
        },
        /**
         * 查看标准 pdf弹框 点击
         */
        testDialogClick() {
            this.testDialogVisible = true;
        },
        
        /**
         * 开始检测 步骤二 
         * 上传图片 方法
         */
        // 文件上传成功
        handleAvatarSuccess(res, file) {
            this.secondTest.imageUrl = res;
            this.secondTest.imageName = file.name;
        },
        // 文件上传之前
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/JPG' || file.type === 'image/PNG';
            // const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.warning('请上传图片!');
            }
            // if (!isLt2M) {
            //     this.$message.error('上传头像图片大小不能超过 2MB!');
            // }
            return isJPG;
        },
        // 文件上传失败
        handleAvatarError() {
            this.$message.error("文件上传失败，请稍后重试！")
        },
        /**
         * 确定计算前 调用接口 获取 所需参数
         */
        getDefiniteParams() {

            let params = { "img_url": this.secondTest.imageUrl, "current_user_id": this.options.create_user_id || GLOBAL_CONFIG.userId, rice_evaluate_id: this.options.id || "", "img_ori_name": this.secondTest.imageName }
            return new Promise((resolve, reject) => {
                tpHttp.post(this, "action=com.top.riceInstituteQuality.riceAnalysis.save", { param: JSON.stringify(params) }, (data, code, message) => {
                    if (code == 0 && data) {
                        this.secondTest.imageId = data;
                        resolve(data)
                    } else {
                        reject(message)
                    }
                })
            })
        },
        /**
         * 确定计算点击
         */
        definiteCalculationClick() {
            if (!this.secondTest.imageUrl) {
                this.$message.warning("请先上传图片 ！")
                return
            }
            this.definiteLoading = true;
            try {
                this.getDefiniteParams().then(res => {
                    this.definiteHandel(res).then(res => {
                        this.definiteLoading = false;
                        this.testActice = 2
                    }).catch(err => {
                        this.definiteLoading = false;
                        this.$message.error("计算失败，请稍后重试 或 自行填写相关标准！")
                        this.testActice = 2
                    })
                }).catch(message => {
                    this.definiteLoading = false;
                    this.$message.error("计算失败，请稍后重试 或 自行填写相关标准！")
                    this.testActice = 2
                })
            } catch {
                this.definiteLoading = false;
                this.$message.error("计算失败，请稍后重试 或 自行填写相关标准！")
                this.testActice = 2
            }

        },
        /**
         * 确定计算方法处理
         */
        definiteHandel(res) {
            let params = { "imgId": res }
            return new Promise((resolve, reject) => {

                setTimeout(() => {
                    clearInterval(time)
                    reject("时间到啦")
                }, 5000)
                let time = setInterval(() => {
                    tpHttp.post(this, "action=com.top.riceInstituteQuality.riceAnalysis.get", { param: JSON.stringify(params) }, (data, code, message) => {
                        if (code == 0 && data?.analysis_result) {
                            clearInterval(time)
                            this.thirdResults.zjml = data.analysis_result?.numWN.toFixed(2)*100 ?? ""
                            this.thirdResults.ebd = data.analysis_result?.chalk.toFixed(2)*100 ?? ""
                            this.thirdResults.tmd = data.analysis_result?.tranparency ?? ""
                            resolve();
                        } else {
                        }
                    })
                }, 500)
            })
        },
        /**
         * 拼装评价提交参数
         * @returns { * }  评价提交参数
         */
        evaluateParams() {
            let params = {
                "current_user_id": this.options.create_user_id || "",
                "test_result": {
                    "cook_eat_sense": this.thirdResults.ggpf,
                    "cook_eat_subtraction": this.thirdResults.jxz,
                    "cook_eat_gel_consistency": this.thirdResults.jcd,
                    "cook_eat_amylose": this.thirdResults.zldf,
                    "sample_weight": this.riceSource.sampleWeight,
                    "test_basis": this.riceSource.testBasis
                },
                "rice_source": {
                    "rice_evaluate_id": this.options.id || "",
                    "apply_number": this.riceSource.number,
                    "seed_rice_id": this.riceSource.seedRice,
                    "seed_rice_name": this.getSeedRiceName(this.riceSource.seedRice,this.seedRiceList,"id","variety_name"),
                    "rice_species": this.riceSource.riceSpecies,
                    "sow_date": this.riceSource.date,
                    "remark": this.options.remark || "",
                    "point_id": this.options.point_id || "",
                    "img_id": this.secondTest.imageId,
                    "submitted_by": this.options.submitted_by || "",
                    "phone": this.riceSource.phone,
                    "location": this.options.location || "",
                    "address": this.options.address || "",
                    "send_rice_backup": this.options.send_rice_backup || "",
                    "create_user_id": GLOBAL_CONFIG.userId()
                }
            }
            if (this.riceSource.riceSpecies == 1) {
                params.test_result.whole_rice_precision_long = this.thirdResults.zjmlcl
                params.test_result.whole_rice_precision_middle = this.thirdResults.zjmlzl
                params.test_result.whole_rice_precision_short = this.thirdResults.zjmldl
                params.test_result.evil_whiteness = this.thirdResults.ebd
                params.test_result.pellucidity = this.thirdResults.tmd
            } else if (this.riceSource.riceSpecies == 2) {
                params.test_result.whole_rice_precision = this.thirdResults.zjml
                params.test_result.evil_whiteness = this.thirdResults.ebd
                params.test_result.pellucidity = this.thirdResults.tmd
            } else if (this.riceSource.riceSpecies == 3) {
                params.test_result.whole_rice_precision_long = this.thirdResults.zjmlcl
                params.test_result.whole_rice_precision_middle = this.thirdResults.zjmlzl
                params.test_result.whole_rice_precision_short = this.thirdResults.zjmldl
                params.test_result.negative_rate = this.thirdResults.ynml
                params.test_result.whiteness = this.thirdResults.bd
            } else if (this.riceSource.riceSpecies == 4) {
                params.test_result.whole_rice_precision = this.thirdResults.zjml
                params.test_result.negative_rate = this.thirdResults.ynml
                params.test_result.whiteness = this.thirdResults.bd
            }
            return params
        },
        /**
         * 底部评价点击
         */
        evaluateClick() {
            let objAll = { ...this.riceSource, ...this.secondTest, ...this.thirdResults }
            let oks = true
            for (let v in objAll) {
                if (!objAll[v] && objAll[v] !== 0) {
                    oks = false
                }
            }
            if (!oks) {
                this.$message.warning("请先完善数据 ！")
                return
            }
            tpHttp.post(this, "action=com.top.riceInstituteQuality.qualityEva.appraise", { param: JSON.stringify(this.evaluateParams()) }, (data, code, message) => {
                if (code == 0 && data?.grade_result) {
                    this.testResultData = data.grade_result;
                    this.testActice = 3;
                    this.testResultDialog = true;
                } else if(code == -2){
                    this.$message.error(message)
                } else {
                    this.$message.error("检测失败，请稍后重试！")
                }
            })
        },
        /**
         * 检测结果弹框确认点击
         */
        testResultDialogDefin() {
            this.$emit("test-result-defin")
        },
        /**
         * 检测结果弹框重检点击
         */
        testRecheckDialog() {
            this.testActice = 2
            this.testResultDialog = false;
        },
        /**
         * 获取种植户下拉列表
         */
        getPlanterList() {
            tpHttp.post(this, "action=com.top.localMode.SysUser.getGrowBigFamilyUser", {}, (data, code, message) => {
                if (code == 0 && data?.length) {
                    this.planterList = data;
                } else {
                    this.planterList = [];
                }
            })
        }
    },
    mounted() {
        if (this.dialogSource == 1) {
            this.getApplyNumber();
        }
        // 获取种植用户下拉
        this.getPlanterList();
    }
}
Vue.component("quality-inspection-test-com", qualityInspectionTestCom)